'use strict';

const txl = require('txl');
const util = require('util');

module.exports = {

  /**
   * 填充模版函数
   * @param {String} content 短信模版
   * @param {Object} options 模版参数
   * @return {String} 填充完毕的模版
   */
  template(content, options) {
    return txl(content)(options);
  },

  /**
   *
   * @param {String} urlInfo 请求节点
   * @param {参数} params 参数
   */
  async http(urlInfo,params) {
    const appInfo = this.app.config.tinfor;
    this.app.logger.info("请求地址信息：%s,---参数为：%s",JSON.stringify(urlInfo),JSON.stringify(params));

    const client = this.app.apiClient( appInfo.key,appInfo.secrect,urlInfo.url);

    try {
      const response = await new Promise((resolve, reject) => {
        client.executeWithHeader(urlInfo.method,
          params,
          {},
          function (error,response) {
            if(!error) {
              resolve(response);
            }
            else reject(error);
        });
      });

      this.app.logger.info(response);
     return response;
    } catch(error) {
      this.app.logger.info("三方返回异常错误信息%s",JSON.stringify(error) );
      let msg = this.app.lodash.get(error,"msg","");

      if( error.code === 27 && msg === "Invalid session") {
        this.ctx.throw(401, '登陆过期, 请重新登陆'); //是否为回话失败
      }else {
        // return error;
        this.ctx.throw(500, '服务异常'); // 如果失败，直接抛出异常
      }
    }
  },

  async dingHttp(urlInfo,params) {
    const appInfo = this.app.config.tinfor;
    this.app.logger.info("请求地址信息：%s",JSON.stringify(urlInfo));
    const client = this.app.apiClient( appInfo.key,appInfo.secrect,urlInfo.url);

    try {
      const response = await new Promise((resolve, reject) => {
        client.execute(urlInfo.method,
          params,
          function (error,response) {
            if(!error) {
              resolve(response);
            }
            else reject(error);

        });
      });

      this.app.logger.info(response);
     return response;
    } catch(error) {
      this.app.logger.info("三方返回异常错误信息%s",JSON.stringify(error) );
      if(error.code === 15) {
        this.ctx.throw(401, '登陆过期, 请重新登陆'); //是否为回话失败
      }else {
        this.ctx.throw(500, '服务异常'); // 如果失败，直接抛出异常
      }
    }
  },

   /**
   *根据身份证提取性别
   * @param {string} idCard 身份证号码
   * @return {string} 性别
   */
  getSexByIDCard(idCard) {
    const idxSexStart = (idCard.length === 15 ? 14 : 16);
    const idxSex = 1 - idCard.substr(idxSexStart, 1) % 2;
    return parseInt(idxSex) === 1 ? 2 : 1;
  },

  filter_insert_sql(str) {
    if (!str) {
      return '';
    }
    return str.replace(/'/g, '\\\'');
  },

  /**
   * 通过身份证号码获取获取出身日期
   * @param {string} idCard 身份证号码
   */
  getBirthdayFromIdCard (idCard) {
    var birthday = "0000-00-00";
    if(idCard != null && idCard != ""){
        if(idCard.length == 15){
            birthday = "19"+idCard.substr(6,6);
        } else if(idCard.length == 18){
            birthday = idCard.substr(6,8);
        }

        birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
    }

    return birthday;
  },

  cloneObjectFn(obj) { // 对象复制

    return JSON.parse(JSON.stringify(obj));
  },

  // 比较数组大小
  compareVersionUpdate(latest, current) {
    const n = latest.length;
    let i = 0;
    while (i < n) {
      if (parseInt(latest[i]) < parseInt(current[i])) return true;
      if (parseInt(latest[i]) > parseInt(current[i])) return false;
      i++;
    }
    return true;
  },

  isProd() {
    const { app } = this;
    return app.config.env !== 'local'
        && app.config.env !== 'unittest'
        && app.config.env !== 'sit';
  },

  // 检查身份证是否符合要求
  checkAge(id_card) {

    const currentYear = new Date().getFullYear();
    const birthYear = parseInt(id_card.substr(6, 4));
    const age = currentYear - birthYear;

    return !!((age < 18 || age > 60));
  },
};
